package com.parkinginfo.manager;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class DatabaseConnection {
	
	public static Context father;
	
	public static float lat = 0.0f;
	public static float lng = 0.0f;
	public static double distance = 10.0;
	
	
	public final int GET_PROPERTIES = 0;
	public final int GET_SEARCH = 1;
	public final int GET_LOGIN = 2;
	public final int GET_ADD = 3;
	
	public final String GET_PROPERTIES_ADDR = "http://cmpeestate.webege.com/getProperties.php";
	public final String GET_SEARCH_ADDR = "http://cmpeestate.webege.com/searchProperty.php";
	public final String GET_LOGIN_ADDR = "http://cmpeestate.webege.com/login.php";
	public final String GET_ADD_ADDR = "http://cmpeestate.webege.com/addProperty.php";
	
	public static String search_area = "";
	public static String search_term = "";
	
	public static ArrayList<Property> loaded;
	
	public static Boolean logged = false;
	
	void getProperties(){
		JSONArray ja = getServerData(GET_PROPERTIES);
		if(ja == null ) {
			return;
		}
		//Se o resultado vier vazio...
		else {
			if(ja.length() == 0) {
				return;
			}
		}
		loaded= new ArrayList<Property>();
		if( ja != null ){
			JSONArray jsonProperty;
			try {
				for(int i=0;i < ja.length(); i++){
					jsonProperty = ja.getJSONArray(i);
					Property company = parsePropertyData(jsonProperty);
					loaded.add(company);
				}
			} catch (JSONException e) {
				Log.e("log_tag", "(Database getProperty()) Erro a obter jsonProperty "+e.toString());
				e.printStackTrace();
			}
		}
	}
	
	public void SearchProperties(){
		JSONArray ja = getServerData(GET_SEARCH);
		
		if(ja == null ) {
			return;
		}
		//Se o resultado vier vazio...
		else {
			if(ja.length() == 0) {
				return;
			}
		}

		loaded= new ArrayList<Property>();
		//Toast.makeText(father, ""+ja.length(), Toast.LENGTH_SHORT).show();
		if( ja != null ){
			JSONArray jsonProperty;
			try {
				for(int i=0;i < ja.length(); i++){
					jsonProperty = ja.getJSONArray(i);
					Property company = parsePropertyData(jsonProperty);
					loaded.add(company);
				}
			} catch (JSONException e) {
				Log.e("log_tag", "(Database searchProperty()) Erro a obter jsonProperty "+e.toString());
				e.printStackTrace();
			}
		}
	}
	
	String login_status = "";
	public void logIn(){
		getServerData(GET_LOGIN);
		if(login_status.length()>0){
			if(login_status.contains("success")){
				DatabaseConnection.logged=true;
				Toast.makeText(father, "Logged in with success", Toast.LENGTH_LONG).show();
				return;
			}
		}
		Toast.makeText(father, "Log-in in failed", Toast.LENGTH_LONG).show();
	}
	
	
	ArrayList<NameValuePair> toAddPairs = new ArrayList<NameValuePair>();
	public void addProperty(String name, String address, String description, String city, String zipcode, 
			String state, String latitude, String longitude){			

		toAddPairs.add(new BasicNameValuePair("name",name));
		toAddPairs.add(new BasicNameValuePair("address",address));
		toAddPairs.add(new BasicNameValuePair("description",description));
		toAddPairs.add(new BasicNameValuePair("city",city));
		toAddPairs.add(new BasicNameValuePair("zipcode",zipcode));
		toAddPairs.add(new BasicNameValuePair("state",state));
		toAddPairs.add(new BasicNameValuePair("latitude",latitude));
		toAddPairs.add(new BasicNameValuePair("longitude",longitude));
		getServerData(GET_ADD);
	}
	
	private Property parsePropertyData(JSONArray ja){
		Property c = new Property();
		JSONObject json_data;

		if(ja != null){
			try {
				for(int i=0;i<ja.length();i++){

					json_data = ja.getJSONObject(i);

					String name = json_data.getString("name");
					String value = json_data.getString("value");

					if(name.equals("id"))
						c.id = Integer.parseInt(value);
					
					else if(name.equals("name"))
						c.name = value;

					else if(name.equals("address"))
						c.address = value;

					else if(name.equals("description"))
						c.description = value;

					else if(name.equals("city"))
						c.city = value;

					else if(name.equals("zipcd"))
						c.zipcode = value;

					else if(name.equals("state"))
						c.state = value;
					
					else if(name.equals("longitude"))
						c.longitude = Float.parseFloat(value);
					
					else if(name.equals("latitude"))
						c.latitude = Float.parseFloat(value);
					
					else if(name.equals("pictures"))
						c.images.add(value);
					
					else if(name.equals("videos"))
						c.videos.add(value);
					
					else if(name.equals("agent_name"))
						c.agent_name = value;
					
					else if(name.equals("agent_number"))
						c.agent_number = value;
					
					else if(name.equals("Price"))
						c.price = value;
					}

			} catch (JSONException e) {
				e.printStackTrace();
				Log.e("log_tag", "(Database parsePropertyData()) Erro " + e.toString());
			}
		}
		return c;
	}
	
	
	
	private JSONArray getServerData(int scriptType) {
		
		InputStream is = null;
		String result = "";
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		HttpParams httpParameters = new BasicHttpParams();

		//Tempo maximo ate se estabelecer uma ligacao
		HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
		// Tempo maximo para esperar uma resposta depois de estabelecida a ligacao
		HttpConnectionParams.setSoTimeout(httpParameters, 50000);

		HttpClient httpclient = new DefaultHttpClient(httpParameters);
		try{
			HttpPost httppost = null;
			//dependendo do tipo de query acima definido, sao necessarios diferentes scripts
			
			switch(scriptType){
				case GET_PROPERTIES: httppost = new HttpPost(GET_PROPERTIES_ADDR);
					nameValuePairs.add(new BasicNameValuePair("lat",Float.toString(lat)));
					nameValuePairs.add(new BasicNameValuePair("lon",Float.toString(lng)));
					nameValuePairs.add(new BasicNameValuePair("distance",Double.toString(distance)));
					break;
				case GET_SEARCH:
					httppost = new HttpPost(GET_SEARCH_ADDR);
					nameValuePairs.add(new BasicNameValuePair(search_area,search_term));
					break;
				case GET_LOGIN:
					httppost = new HttpPost(GET_LOGIN_ADDR);
					nameValuePairs.add(new BasicNameValuePair("username",search_area));
					nameValuePairs.add(new BasicNameValuePair("password",search_term));
					break;
				case GET_ADD:
					httppost = new HttpPost(GET_ADD_ADDR);
					nameValuePairs = toAddPairs;
					break;			
			}
			
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpclient.execute(httppost);

			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();

				is = entity.getContent();

			}

		}catch(Exception e){
			httpclient.getConnectionManager().shutdown();
			Log.e("log_tag", "(Database getServerData()) Error in http connection "+e.toString());
			return null;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			line = reader.readLine();
			
			if(scriptType == GET_LOGIN){
				login_status = line;
				return null;
			}

			if(scriptType == GET_ADD){
				Toast.makeText(father, line, Toast.LENGTH_SHORT).show();
				return null;
			}
			
			sb.append(line + "\n");
			//Log.d("log_tag", "LINE: "+sb);
			is.close();
			result=sb.toString();

		}catch(Exception e){
			Log.e("log_tag", "(Database getServerData())  Error converting result "+e.toString());
			return null;
		}
		
		//parse json data
		try{

			//Log.v("log_tag", result);
			return new JSONArray(result);

		}catch(JSONException e){
			Log.e("log_tag", "(Database getServerData()) Error parsing data "+result);
		}
		
		return null;
	}
}
